package com.corpgovernment.organization.controller;

import com.corpgovernment.api.organization.model.backuser.BackgroundUserVo;
import com.corpgovernment.api.organization.model.idcard.UserIdCardVo;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.enums.ExceptionCodeEnum;
import com.corpgovernment.organization.convert.EmployeeInfoConvert;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.entity.db.MbOrgEmployeeInfo;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.entity.db.MbOrgUserIdcard;
import com.corpgovernment.organization.service.IBackgroundUserService;
import com.corpgovernment.organization.service.IOrgUserIdCardService;
import com.corpgovernment.organization.service.IOrganizationEmployeeService;
import com.corpgovernment.organization.service.IOrganizationInfoService;
import com.corpgovernment.organization.service.impl.BackgroundUserService;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import org.apache.commons.collections.MapUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台用户controller
 *
 * @author wangyujue
 */
@Api(tags = "后台用户")
@RestController
@RequestMapping("/backgroundUser")
public class BackgroundUserController {

	@Autowired
	private IOrganizationInfoService organizationInfoService;
	@Autowired
	private IOrganizationEmployeeService organizationEmployeeService;
	@Autowired
	private IOrgUserIdCardService organizationUserIdCardService;
	@Autowired
	private IBackgroundUserService backgroundUserService;

	/**
	 * 通过组织结构id查找父级所有组织结构id，一直到顶级子公司
	 *
	 * @param request 用户vo
	 * @return JSONResult
	 */
	@RequestMapping(value = "/createOrUpdateUser")
	public JSONResult<Boolean> createOrUpdateUser(@RequestBody BackgroundUserVo request) {
		return JSONResult.success(backgroundUserService.createOrUpdateUser(request));
	}


	/**
	 * 通过uid删除用户，逻辑删除
	 *
	 * @param uid 用户id
	 * @return JSONResult
	 */
	@RequestMapping(value = "/deleteUser")
	@Transactional(rollbackFor = Exception.class)
	public JSONResult<Boolean> deleteUser(@RequestParam(name = "uid") String uid) {
		// 删除用户信息
		boolean delete = organizationEmployeeService.deleteByUid(uid);
		if (!delete) {
			throw new CorpBusinessException(ExceptionCodeEnum.Alert, "删除用户失败");
		}
		// 删除用户证件信息
		organizationUserIdCardService.deleteByEmployeeUid(uid);
		return JSONResult.success(true);
	}

	/**
	 * 获得单个用户
	 *
	 * @param uid 用户id
	 * @return JSONResult
	 */
	@RequestMapping(value = "/findUserByUid")
	public JSONResult<BackgroundUserVo> findUserByUid(@RequestParam String uid) {
		// 通过uid获得某个用户
		MbOrgEmployeeInfo mbOrgEmployeeInfo = organizationEmployeeService.findByUid(uid);
		if (mbOrgEmployeeInfo == null) {
			return new JSONResult<>(null);
		}
		BackgroundUserVo backgroundUserVo = new BackgroundUserVo();
		BeanUtils.copyProperties(mbOrgEmployeeInfo, backgroundUserVo);

		// 获得用户的证件信息
		List<MbOrgUserIdcard> cardList = organizationUserIdCardService.findByEmployeeUid(uid);
        List<UserIdCardVo> cardVoList = new ArrayList<>();
        for (MbOrgUserIdcard mbOrgUserIdcard : cardList) {
            UserIdCardVo userIdCardVo = new UserIdCardVo();
            userIdCardVo.setCardNo(mbOrgUserIdcard.getCardNo());
            userIdCardVo.setCardType(mbOrgUserIdcard.getCardType());
            userIdCardVo.setEmployeeUid(uid);
            cardVoList.add(userIdCardVo);
        }
        backgroundUserVo.setCardList(cardVoList);
        return new JSONResult<>(backgroundUserVo);
    }

	/**
	 * 获得后台管理员列表
	 *
	 * @return JSONResult
	 */
	@ApiOperation("获得后台管理员列表")
	@GetMapping(value = "/listAllUsers")
	public JSONResult<List<BackgroundUserVo>> listAllUsers() {
		List<MbOrgEmployeeInfo> mbOrgEmployeeInfoList = backgroundUserService.listAllUsers();
		List<BackgroundUserVo> backgroundUserVos = EmployeeInfoConvert.convertToBackgroundUser(mbOrgEmployeeInfoList);
		return new JSONResult<>(backgroundUserVos);
	}

//    /**
//     * 获得用户列表，orgId存在优先用orgId查询，key模糊匹配name和uid
//     * url:http://localhost:7890/backgroundUser/listUser?key=&orgId=fuUcOgWItA&pageNum=1&pageSize=10
//     *
//     * @param key   关键字
//     * @param orgId 组织结构id
//     * @return JSONResult
//     */
//    @RequestMapping(value = "/backgroundUser/listUser")
//    JSONResult<Page> listUser(@RequestParam String key,
//                              @RequestParam String orgId,
//                              @RequestParam Integer pageNum,
//                              @RequestParam Integer pageSize) {
//        List<MbOrgEmployeeInfo> employeeInfoList = new ArrayList<>();
//
//        // #1.通过组织id查找组织下所有的人
//        // 查询组织结构下所有组织结构
//        List<String> allChildOrgIds = new ArrayList<>();
//        organizationInfoService.findAllChildOrgIdsByOrgId(orgId, allChildOrgIds);
//        allChildOrgIds.add(orgId);
//        if (StringUtils.isNotBlank(key)) {
//            // #2.通过key模糊匹配uid和name查询
//            employeeInfoList = organizationEmployeeService.fuzzyUserByUidAndNameInOrgs(key, allChildOrgIds);
//        } else {
//            // 通过组织结构id查询出员工信息列表
//            employeeInfoList = organizationEmployeeService.batchFindAllBackgroundByOrgIds(allChildOrgIds, pageNum == null ? CommonConst.PAGE_SIZE_10 : pageNum, pageSize);
//        }
//        if (CollectionUtils.isEmpty(employeeInfoList)) {
//            return new JSONResult<>(new Page(0, 0, 0, 0L, Collections.emptyList()));
//        }
//        PageInfo pageInfo = new PageInfo(employeeInfoList);
//
//        // 先拿到部门名称
//        List<String> orgIds = employeeInfoList.stream()
//                .filter(p -> StringUtils.isNotBlank(p.getOrgId()))
//                .map(MbOrgEmployeeInfo::getOrgId)
//                .distinct()
//                .collect(Collectors.toList());
//        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
//        // 转成map，之后组装返回数据
//        Map<String, String> orgNameMap = mbOrgInfoList.stream()
//                .filter(p -> StringUtils.isNotBlank(p.getName()))
//                .collect(Collectors.toMap(MbOrgInfo::getOrgId, MbOrgInfo::getName));
//
//
//        List<BackgroundUserVo> returnList = new ArrayList<>();
//        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : employeeInfoList) {
//            BackgroundUserVo backgroundUserVo = new BackgroundUserVo();
//            BeanUtils.copyProperties(mbOrgEmployeeInfo, backgroundUserVo);
//            if (MapUtils.isNotEmpty(orgNameMap)) {
//                backgroundUserVo.setOrgName(orgNameMap.get(mbOrgEmployeeInfo.getOrgId()));
//            }
//            returnList.add(backgroundUserVo);
//        }
//        Page page = new Page(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getLastPage(), pageInfo.getTotal(), returnList);
//        return new JSONResult<>(page);
//
//    }

    /**
     * 批量获得用户信息
     *
     * @param uids 用户ids
     * @return JSONResult
     */
    @RequestMapping(value = "/listByUids")
    JSONResult<List<BackgroundUserVo>> listByUids(@RequestParam("uids") List<String> uids) {
        List<MbOrgEmployeeInfo> employeeInfoList = organizationEmployeeService.listBackUserByUids(uids);
        // 先拿到部门名称
        List<String> orgIds = employeeInfoList.stream()
                .filter(p -> StringUtils.isNotBlank(p.getOrgId()))
                .map(MbOrgEmployeeInfo::getOrgId)
                .distinct()
                .collect(Collectors.toList());
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
        // 转成map，之后组装返回数据
        Map<String, String> orgNameMap = mbOrgInfoList.stream()
                .filter(p -> StringUtils.isNotBlank(p.getName()))
                .collect(Collectors.toMap(MbOrgInfo::getOrgId, MbOrgInfo::getName));

        List<BackgroundUserVo> returnList = new ArrayList<>();
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : employeeInfoList) {
            BackgroundUserVo backgroundUserVo = new BackgroundUserVo();
            BeanUtils.copyProperties(mbOrgEmployeeInfo, backgroundUserVo);
            if (MapUtils.isNotEmpty(orgNameMap)) {
                backgroundUserVo.setOrgName(orgNameMap.get(mbOrgEmployeeInfo.getOrgId()));
            }
            returnList.add(backgroundUserVo);
        }
        return JSONResult.success(returnList);
    }

}
